import React, { useEffect } from 'react'
import { useLocation, useNavigate } from 'react-router-dom';
import { RouterRawState, UserRawState } from '../../types';
interface PropsType {
  el: JSX.Element
  route: RouterRawState
}

export const PrivateRouter: React.FC<PropsType> = ({ el, route }) => {
  const token = localStorage.getItem('token');
  const { pathname } = useLocation()
  const navigate = useNavigate()
  const whiteList = ['/login']
  const data = localStorage.getItem('userInfo')
  const userInfo: UserRawState = JSON.parse(data ? data: '{}')
  useEffect(() => {
    if (token) {
      // 已登录
      if (whiteList.includes(pathname)) {
        // 已登录 访问是登录页面
        navigate('/')
      } else {
        // 已登录 访问是非登录页面
        // 验证权限
        if(route.meta.roles && !route.meta.roles.includes(userInfo.role)) {
          navigate('/403')
        }
      }
    } else {
      // 未登录
      if (whiteList.includes(pathname)) {
        // 未登录 访问的是登录页面
      } else {
        // 未登录 访问的是非登录页面
        navigate('/login')
      }
    }
  }, [pathname])

  return el
}